package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.config.OSSConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.json.JsonDateValueProcessor;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.BClientMapper;
import com.youhome.service.model.*;
import com.youhome.service.parameter.ParamClientRegister;
import com.youhome.service.parameter.ParamCompanyClientSearch;
import com.youhome.service.service.*;
import com.youhome.utils.ExcelUtils;
import com.youhome.utils.StringUtils;
import com.youhome.utils.ValidationUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chen365 on 2017/10/25.
 */
@Service
public class BClientServiceImpl implements BClientService {

    @Autowired
    private BClientMapper bClientMapper;
    @Autowired
    private BUserService bUserService;
    @Autowired
    private BCounselorService bCounselorService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private DownloadService downloadService;
    @Autowired
    private BShareGroupService bShareGroupService;
    @Autowired
    private BCompanyService bCompanyService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private OSSConfig ossConfig;

    @Override
    @Transactional
    public int create(BClient client) {
        client.setStatus(1);
        client.setCtime(new Date());
        return bClientMapper.insertSelective(client);
    }

    @Override
    public int update(BClient client) {
        client.setUtime(new Date());
        return bClientMapper.updateByPrimaryKeySelective(client);
    }

    @Override
    public BClient selectByPrimaryKey(Long clientId) throws CustomException {
        return bClientMapper.selectByPrimaryKey(clientId);
    }

    @Override
    public PageInfo<BClient> selectByBean(Integer pageNumber, Integer pageSize, BClient client) {
        if (pageNumber == null || pageNumber < 1)
            pageNumber = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(pageNumber, pageSize);
        List<BClient> list = bClientMapper.selectByBean(client);
        return new PageInfo<>(list);
    }

    @Override
    public List<BClient> selectByBean(BClient client) {
        return bClientMapper.selectByBean(client);
    }

    @Override
    public int delete(BClient client) {
        return bClientMapper.statusDeleteByPrimaryKey(client);
    }

    @Override
    public int isExist(String phone, Long companyId) {
        BClient client = new BClient();
        client.setCompanyId(companyId);
        client.setPhone(phone);
        return bClientMapper.selectIsExistByCompanyIdAndPhone(client);
    }

    @Override
    public List<DateItem> selectLast30DayDateItemByShareGroupUUID(String shareGroupUuid) throws CustomException {
        if (StringUtils.isEmpty(shareGroupUuid)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        return bClientMapper.selectLast30DayDateItemByShareGroupUUID(shareGroupUuid);
    }

    @Override
    public BClient selectByUserId(Long userId) {
        return bClientMapper.selectByUserId(userId);
    }

    @Override
    public BClient updateInvestmentByPrimaryKey(Principal principal, BClient client) throws CustomException {
        Long userId = principal.getUser().getUserId();
        client.setUserId(userId);
        client.setUtime(new Date());
        if (bClientMapper.updateInvestmentByPrimaryKey(client) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
        return client;
    }


    @Override
    public BClient updateByBasicsPrimaryKey(Principal principal, BClient client) throws CustomException {

        Long userId = principal.getUser().getUserId();
        client.setUserId(userId);
        client.setUtime(new Date());
        if (bClientMapper.updateByBasicsPrimaryKey(client) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
        return client;
    }

    @Override
    public boolean selectExistsByPrimaryKey(Long clientId) {
        if (bClientMapper.selectExistsByPrimaryKey(clientId) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public int save(BClient client) {
        if (client.getClientId() != null && client.getClientId() > 0) {
            client.setUtime(new Date());
            return bClientMapper.updateByPrimaryKeySelective(client);
        }
        client.setCtime(new Date());
        return bClientMapper.insertSelective(client);
    }

    @Override
    public String export(Principal principal) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BCounselor counselor = bCounselorService.selectByUserId(userId);
        if (counselor == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }

        BClient client = new BClient();
        client.setCounselorId(counselor.getCounselorId());
        client.setStatus(1);

        try {
            List<BClient> list = selectByBean(client);

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());

            JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
            JSONArray jsonArray2 = new JSONArray();
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) JSONObject.fromObject(obj);

                //性别，0：女，1：男
                String sex = "";
                if (jsonObject.get("sex").toString().equals("1")) {
                    sex = "男";
                } else if (jsonObject.get("sex").toString().equals("0")) {
                    sex = "女";
                }
                jsonObject.put("sex", sex);

                //婚姻，0保密，1已婚，2未婚,3离异
                String marital = "";
                if (jsonObject.get("marital").toString().equals("0")) {
                    marital = "保密";
                } else if (jsonObject.get("marital").toString().equals("1")) {
                    marital = "已婚";
                } else if (jsonObject.get("marital").toString().equals("2")) {
                    marital = "未婚";
                } else if (jsonObject.get("marital").toString().equals("3")) {
                    marital = "离异";
                }
                jsonObject.put("marital", marital);

                //出生年月
                String birthdate = jsonObject.get("birthdate").toString();
                if (!StringUtils.isEmpty(birthdate)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = format.parse(birthdate);
                    birthdate = format.format(date);
                    jsonObject.put("birthdate", birthdate);
                }

                jsonArray2.add(jsonObject);
            }

            if (list.size() > 0) {
                String title = "客户信息";
                Map<String, String> headMap = new LinkedHashMap<String, String>();

                headMap.put("name", "姓名");
                headMap.put("phone", "手机");
                headMap.put("weixin", "微信");
                headMap.put("qq", "QQ");
                headMap.put("investmentObjective", "投资目的");
                headMap.put("capitalSource", "资金来源");
                headMap.put("tendencyRoom", "房型倾向");
                headMap.put("tendencySite", "地点倾向");
                headMap.put("tendencyPrice", "价格倾向");
                headMap.put("tendencySize", "面积倾向");
                headMap.put("province", "省");
                headMap.put("city", "市");
                headMap.put("area", "区");
                headMap.put("address", "详细地址");
                headMap.put("birthdate", "出生日期");
                headMap.put("marital", "婚姻");
                headMap.put("income", "年收入");
                headMap.put("jobTitle", "职称");
                headMap.put("jobType", "工作行业");
                headMap.put("sex", "性别");
                headMap.put("email", "邮箱");
                headMap.put("source", "客户来源");

                String fileName = UUID.randomUUID().toString() + ".xlsx";

                String filePath = "/data/excel/" + fileName;

                OutputStream outXlsx = new FileOutputStream(filePath);

                ExcelUtils.exportExcelX(title, headMap, jsonArray2, "yyyy-MM-dd hh:mm:ss", 0, outXlsx);
                outXlsx.close();
                uploadService.uploadExcel(filePath);
                String url = downloadService.downloadExcel("excel/" + fileName);
                if (!StringUtils.isEmpty(url)) {
                    return url;
                } else {
                    throw new CustomException(ResultCode.DOWNLOAD_FAIL);
                }
            } else {
                throw new CustomException(ResultCode.NO_DATA);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.ERROR);
        }
    }

    @Override
    public PageInfo<BClient> selectByBean(Principal principal, Integer pageNumber, Integer pageSize, String keyword, BClient client) throws CustomException {
        if (!StringUtils.isEmpty(keyword)) {
            if (ValidationUtils.isNumeric(keyword) && keyword.length() >= 3) {
                client.setPhone(keyword);
            } else {
                client.setName(keyword);
            }
        }
        Long userId = principal.getUser().getUserId();
        BCounselor counselor = bCounselorService.selectByUserId(userId);
        if (counselor == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        client.setCounselorId(counselor.getCounselorId());
        client.setStatus(1);
        return selectByBean(pageNumber, pageSize, client);
    }

    @Override
    public BClient register(ParamClientRegister record) throws CustomException {

        //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
        Integer source = record.getSource();
        String id = record.getId();
        String phone = record.getPhone();

        if (source == 1 || source == 3) {
            if (StringUtils.isEmpty(id)) {
                throw new CustomException(ResultCode.ERROR_PARAMETER);
            }
        }

        //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
        if (source == 1 || source == 3 || source == 4) {
            if (StringUtils.isEmpty(record.getMsg()))
                throw new CustomException(ResultCode.EMPTY_SMS_VALIDATE_CODE);

            if (StringUtils.isEmpty(record.getMsgId()))
                throw new CustomException(ResultCode.EMPTY_MSGID);
        }

        try {
            Long companyId = 0L;
            Long counselorId = 0L;

            if (source == 1 && !StringUtils.isEmpty(id)) {
                System.err.println("================================sss========================");
                BShareGroup shareGroup = bShareGroupService.selectByPrimaryKey(id);
                if (shareGroup != null) {
                    counselorId = shareGroup.getCounselorId();
                }
                System.err.println("=================================a==========================");
                BCounselor counselor = bCounselorService.selectByPrimaryKey(counselorId);
                companyId = counselor.getCompanyId();

                if (counselor == null) {
                    throw new CustomException(ResultCode.COUNSELOR_INEXISTENCE);
                }
                System.err.println("=================================b===========================");
                if (isExist(phone, counselor.getCompanyId()) > 0) {
                    throw new CustomException(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
                }
            }
            System.err.println("=================================3============================");
            if (source == 2) {
                BUser currentUser = bUserService.getCurrentUser();
                if (currentUser == null) {
                    throw new CustomException(ResultCode.EXPIRED_LOGIN);
                }
                BCounselor counselor = bCounselorService.selectByUserId(currentUser.getUserId());

                if (counselor == null) {
                    throw new CustomException(ResultCode.COUNSELOR_INEXISTENCE);
                }
                companyId = counselor.getCompanyId();
                counselorId = counselor.getCounselorId();
            }

            if (source == 3 && !StringUtils.isEmpty(id)) {
                BCompany company = bCompanyService.selectByUUID(id);
                if (company == null) {
                    throw new CustomException(ResultCode.NOT_EXIST_COMPANY);
                }
                companyId = company.getCompanyId();

                if (isExist(phone, companyId) > 0) {
                    throw new CustomException(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
                }
            }
            System.err.println("====================================4=========================");
            BUser user = bUserService.selectByPhone(phone);
            if (user == null) {
                BUser bUser = new BUser();
                bUser.setPhone(phone);
                bUser.setCtime(new Date());
                bUser.setEnabled(true);
                user = bUserService.create(bUser);

                BUserRole userRole = new BUserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(3L); //3	ROLE_CLIENT	客户

                bUserService.create(userRole);
            }
            Long userId = user.getUserId();

            BClient client = new BClient();
            client.setUserId(userId);
            client.setCompanyId(companyId);
            client.setCounselorId(counselorId);
            client.setPhone(phone);

            if (isExist(phone, counselorId) > 0) {
                throw new CustomException(ResultCode.CLIENT_REGISTERED_WITH_COUNSELOR);
            }
            System.err.println("=========================5====================================");
            client.setName(record.getName());
            client.setEmail(record.getEmail());
            client.setSource(StringUtils.getSourceText(source));

            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 1) {
                client.setSourceShareGorupUUID(id);
            } else if (source == 3) {
                client.setCompanyUUID(id);
            }

            if (!StringUtils.isEmpty(record.getWeiXin())) {
                client.setWeixin(record.getWeiXin());
            }
            if (!StringUtils.isEmpty(record.getQq())) {
                client.setQq(record.getQq());
            }
            if (!StringUtils.isEmpty(record.getInvestmentObjective())) {
                client.setInvestmentObjective(record.getInvestmentObjective());
            }
            if (!StringUtils.isEmpty(record.getCapitalSource())) {
                client.setCapitalSource(record.getCapitalSource());
            }
            if (!StringUtils.isEmpty(record.getTendencyRoom())) {
                client.setTendencyRoom(record.getTendencyRoom());
            }
            if (!StringUtils.isEmpty(record.getTendencySite())) {
                client.setTendencySite(record.getTendencySite());
            }
            if (!StringUtils.isEmpty(record.getTendencyPrice())) {
                client.setTendencyPrice(record.getTendencyPrice());
            }
            if (!StringUtils.isEmpty(record.getTendencySize())) {
                client.setTendencySize(record.getTendencySize());
            }
            if (!StringUtils.isEmpty(record.getTendencySchool())) {
                client.setTendencySchool(record.getTendencySchool());
            }
            if (!StringUtils.isEmpty(record.getProvince())) {
                client.setProvince(record.getProvince());
            }
            if (!StringUtils.isEmpty(record.getCity())) {
                client.setCity(record.getCity());
            }
            if (!StringUtils.isEmpty(record.getArea())) {
                client.setArea(record.getArea());
            }
            if (!StringUtils.isEmpty(record.getAddress())) {
                client.setAddress(record.getAddress());
            }
            if (!StringUtils.isEmpty(record.getBirthDate())) {
                client.setBirthdate(record.getBirthDate());
            }
            if (!StringUtils.isEmpty(record.getMarital())) {
                client.setMarital(record.getMarital());
            }
            if (!StringUtils.isEmpty(record.getIncome())) {
                client.setIncome(record.getIncome());
            }
            if (!StringUtils.isEmpty(record.getJobTitle())) {
                client.setJobTitle(record.getJobTitle());
            }
            if (!StringUtils.isEmpty(record.getJobType())) {
                client.setJobType(record.getJobType());
            }
            if (!StringUtils.isEmpty(record.getSex())) {
                client.setSex(record.getSex());
            } else {
                client.setSex(0);
            }
            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 2) {
                if (create(client) == 1) {
                    return client;
                }
            }
            //1.分享注册,2.顾问创建,3.B端注册,4.C端注册
            if (source == 1 || source == 3 || source == 4) {
//                JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
//                ValidSMSResult result = jsmsClient.sendValidSMSCode(msgId, msg);
//                if (result.getIsValid()) {
//                    if (bClientService.save(client) == 1) {
//                        return new Result(ResultCode.SUCCESS, client);
//                    }
//                } else {
//                    return new Result(ResultCode.ERROR_VALIDATE_CODE);
//                }

                if (create(client) == 1) {
                    return client;
                }
            }

        }

        /*catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
            Integer ErrorCode = e.getErrorCode();
            if (ErrorCode == 50010) {
                return new Result(ResultCode.CAPTCHA_CODE);
            }
            if (ErrorCode == 50011) {
                return new Result(ResultCode.VERIFICATION_CODE_EXPIRATION);
            }
            if (ErrorCode == 50012) {
                return new Result(ResultCode.VERIFICATION_CODE_HAS_BEEN_VALIDATED);
            }
            if (ErrorCode == 50014) {
                return new Result(ResultCode.CAN_SEND_SHORT_MESSAGE_MARGIN_SHORT);
            }
            if (ErrorCode == 50015) {
                return new Result(ResultCode.VERIFY_CODE_IS_EMPTY);
            }
            if (ErrorCode == 50034) {
                return new Result(ResultCode.SEND_REPEATEDLY);
            }
        }

        */ catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println("====================================7=========================");

        return null;
    }

    @Override
    public int deleteByClientId(Principal principal, Long clientId) throws CustomException {
        if (StringUtils.isEmpty(clientId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        Long userId = principal.getUser().getUserId();
        BCounselor counselor = bCounselorService.selectByUserId(userId);
        if (counselor == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        BClient client = new BClient();
        client.setClientId(clientId);
        client.setCounselorId(counselor.getCounselorId());
        client.setStatus(0);

        return delete(client);
    }

    @Override
    public String companyExport(Principal principal) throws CustomException {
        BClient client = new BClient();

        try {
            Long userId = principal.getUser().getUserId();
            BCompany company = bCompanyService.selectByUserId(userId);
            if (company == null) {
                throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
            }
            client.setCompanyId(company.getCompanyId());

            client.setStatus(1);

            List<BClient> list = selectByBean(client);

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());

            JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
            JSONArray jsonArray2 = new JSONArray();
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) JSONObject.fromObject(obj);
                //性别，0：女，1：男
                jsonObject.put("sex", StringUtils.getMarital(jsonObject.get("sex").toString()));

                //婚姻，0保密，1已婚，2未婚,3离异
                jsonObject.put("marital", StringUtils.getMarital(jsonObject.get("marital").toString()));

                //出生年月
                String birthdate = jsonObject.get("birthdate").toString();
                if (!StringUtils.isEmpty(birthdate)) {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    Date date = format.parse(birthdate);
                    birthdate = format.format(date);
                    jsonObject.put("birthdate", birthdate);
                }

                jsonArray2.add(jsonObject);
            }

            if (list.size() > 0) {
                String title = "客户信息";
                Map<String, String> headMap = new LinkedHashMap<String, String>();

                headMap.put("counselorName", "所属顾问");
                headMap.put("name", "姓名");
                headMap.put("phone", "手机");
                headMap.put("weixin", "微信");
                headMap.put("qq", "QQ");
                headMap.put("investmentObjective", "投资目的");
                headMap.put("capitalSource", "资金来源");
                headMap.put("tendencyRoom", "房型倾向");
                headMap.put("tendencySite", "地点倾向");
                headMap.put("tendencyPrice", "价格倾向");
                headMap.put("tendencySize", "面积倾向");
                headMap.put("province", "省");
                headMap.put("city", "市");
                headMap.put("area", "区");
                headMap.put("address", "详细地址");
                headMap.put("birthdate", "出生日期");
                headMap.put("marital", "婚姻");
                headMap.put("income", "年收入");
                headMap.put("jobTitle", "职称");
                headMap.put("jobType", "工作行业");
                headMap.put("sex", "性别");
                headMap.put("email", "邮箱");
                headMap.put("source", "客户来源");

                String fileName = UUID.randomUUID().toString() + ".xlsx";

                String filePath = "/data/excel/" + fileName;

                OutputStream outXlsx = new FileOutputStream(filePath);

                System.out.println("正在导出xlsx....");
                Date beginTime = new Date();
                ExcelUtils.exportExcelX(title, headMap, jsonArray2, "yyyy-MM-dd hh:mm:ss", 0, outXlsx);
                System.out.println("共" + list.size() + "条数据,执行" + (new Date().getTime() - beginTime.getTime()) + "ms");
                outXlsx.close();
                uploadService.uploadExcel(filePath);
                String url = downloadService.downloadExcel("excel/" + fileName);
                if (!StringUtils.isEmpty(url)) {
                    return url;
                } else {
                    throw new CustomException(ResultCode.DOWNLOAD_FAIL);
                }
            } else {
                throw new CustomException(ResultCode.NO_DATA);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(ResultCode.ERROR);
        }
    }


    @Override
    public BClient selectDetail(Principal principal) throws CustomException {
        Long userId = principal.getUser().getUserId();
        return bClientMapper.selectByUserId(userId);
    }

    @Override
    public void updatePhoto(Principal principal, String photo) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BClient bClient = new BClient();
        bClient.setPhoto(photo);
        bClient.setUserId(userId);
        if (bClientMapper.updatePhotoByUserId(bClient) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public PageInfo<BClient> selectCompanyClientByBean(Principal principal, ParamCompanyClientSearch map) throws CustomException {

        String keyword = map.getKeyword();
        BClient client = new BClient();
        if (!StringUtils.isEmpty(keyword)) {
            if (ValidationUtils.isNumeric(keyword) && keyword.length() >= 3) {
                client.setPhone(keyword);
            } else {
                client.setName(keyword);
            }
        }

        Long userId = principal.getUser().getUserId();
        BCompany company = bCompanyService.selectByUserId(userId);
        if (company == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        client.setCompanyId(company.getCompanyId());
        client.setStatus(1);

        client.setTagId(map.getTagId());
        client.setCounselorId(map.getCounselorId());
        client.setSource(map.getSource());
        client.setSortField(map.getSortField());
        client.setDirection(map.getDirection());
        client.setShowMail(map.getShowMail());
        client.setBtime(map.getBtime());
        client.setEtime(map.getEtime());

        Integer pageNumber = map.getPageNumber();
        Integer pageSize = map.getPageSize();

        if (pageNumber == null || pageNumber < 1)
            pageNumber = 1;

        if (pageSize == null || pageSize < 1)
            pageSize = 10;

        PageHelper.startPage(pageNumber, pageSize);
        List<BClient> list = bClientMapper.selectByBean(client);
        return new PageInfo<>(list);
    }

    /**
     * WX小程序更新客户信息
     *
     * @param request
     * @param client
     * @throws CustomException
     */
    @Override
    public void updateOfWXUpdate(HttpServletRequest request, BClient client) throws CustomException {
        BUser user = tokenService.getUserByToken(request);
        BClient entity = bClientMapper.selectByUserId(user.getUserId());
        if (entity != null) {
            client.setClientId(entity.getClientId());
        } else {
            client.setUserId(user.getUserId());
            client.setPhone(user.getPhone());
        }
        if (save(client) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public PageInfo<BClient> selectByBean(String phone, Integer pageNumber, Integer pageSize) throws CustomException {

        BUser bUser = bUserService.selectByPhone(phone);
        BClient record = new BClient();
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor != null) {
            record.setCounselorId(bCounselor.getCounselorId());
        }

        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }

        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<BClient> list = bClientMapper.selectByBean(record);
        for (BClient client : list) {
            if (!StringUtils.isEmpty(client.getPhoto())) {
                client.setPhoto(ossConfig.getDomain() + client.getPhoto());
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public BClient selectByClientIdOfMobile(Long clientId) throws CustomException {
        BClient bClient = bClientMapper.selectByPrimaryKey(clientId);
        if (bClient == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        if (!StringUtils.isEmpty(bClient.getPhoto())) {
            bClient.setPhoto(ossConfig.getDomain() + bClient.getPhoto());
        }
        return bClient;
    }

    @Override
    public void deleteByClientId(String phone, Long clientId) throws CustomException {

        BUser bUser = bUserService.selectByPhone(phone);
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor == null) {
            throw new CustomException(ResultCode.LAND_EXPIRATION);
        }
        BClient bClient = new BClient();
        bClient.setClientId(clientId); //客户ID
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        if (bClientMapper.deleteByClientIdAndCounselorId(bClient) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void create(String phone, BClient client) throws CustomException {
        BUser bUser = bUserService.selectByPhone(phone);
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor == null) {
            throw new CustomException(ResultCode.LAND_EXPIRATION);
        }
        BClient bClient = new BClient();
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        bClient.setCompanyId(bCounselor.getCompanyId()); //公司ID
        String photo = client.getPhoto();
        if (!StringUtils.isEmpty(photo)) {
            photo = photo.replaceAll(ossConfig.getDomain(), ""); //去掉 oss url
            bClient.setPhoto(photo);
        }
        client.setStatus(1);
        client.setCtime(new Date());
        if (bClientMapper.insertSelective(client) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void updateOfMobile(String phone, BClient map) throws CustomException {

        BUser bUser = bUserService.selectByPhone(phone);
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor == null) {
            throw new CustomException(ResultCode.LAND_EXPIRATION);
        }
        BClient bClient = new BClient();
        bClient.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        bClient.setCompanyId(bCounselor.getCompanyId()); //公司ID
        bClient.setPhone(phone);
        String photo = bClient.getPhoto();
        if (!StringUtils.isEmpty(photo)) {
            photo = photo.replaceAll(ossConfig.getDomain(), ""); //去掉 oss url
            bClient.setPhoto(photo);
        }
        bClient.setUtime(new Date());
        if (bClientMapper.updateByClientIdAndCounselorId(bClient) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }


}
